import React, { useState, useEffect } from 'react';
import PageTitle from '@/components/PageTitle';
import TagTitle from '@/components/TagTitle';
import { Button, DatePicker, Form, Input, message } from 'antd';
import UplodFile from '@/components/FileUpload/UplodFile';
import { connect } from 'umi';
import AddressSelect from '@/components/AddressSelect';
import { setAddressList, setAddressValue } from '@/utils/utils';
import moment from 'moment';
import { generationUploadWorksInfo, insertWorksInfo, queryByIdWorksInfo, updateWorksInfo } from '@/services/addworks';
import { PlusOutlined } from '@ant-design/icons';

interface areaType {
  name?: string;
  value?: string;
  colon?: boolean;
}

const AddWorksTwo = props => {
  const [form] = Form.useForm();
  let { dispatch, history, location, worksData } = props;
  let { disableds, id, ids, isnext } = location?.query ?? {};
  let area: areaType[] = [
    {
      name: '创作方式',
      value: 'creativeMethods',
    },
    {
      name: '创作工具',
      value: 'creativeTools',
    },
    {
      name: '创作周期',
      value: 'creativeCycle',
    },
    {
      name: '作品材质',
      value: 'creativeMaterials',
    },
    {
      name: '制印方式',
      value: 'printingMethod',
    },
    {
      name: '设计元素',
      value: 'designElements',
    },
    {
      name: '字体类型',
      value: 'fontType',
    },
  ];

  /**
   * 提交表单
   * @param values
   */
  const onFinish = values => {
    /**
     * 处理所有的图片数据如果有赋值，如果没有则唯空
     */
    let worksPicture = [
      worksData?.printingSurfaceImg
        ? {
            pictureId: worksData?.printingSurfaceImg ?? '',
            pictureKey: 'printing',
          }
        : '',
      worksData?.imprintingImg
        ? {
            pictureId: worksData?.imprintingImg ?? '',
            pictureKey: 'imprinting',
          }
        : '',
      worksData?.frameOneImg
        ? {
            pictureId: worksData?.frameOneImg ?? '',
            pictureKey: 'frameA',
          }
        : '',
      worksData?.frameTwoImg
        ? {
            pictureId: worksData?.frameTwoImg ?? '',
            pictureKey: 'frameB',
          }
        : '',
      worksData?.frameThreeImg
        ? {
            pictureId: worksData?.frameThreeImg ?? '',
            pictureKey: 'frameC',
          }
        : '',
      ...(values?.imprintingImgs?.length
        ? values?.imprintingImgs.map((el: any, index: number) => ({
            pictureId: el?.value,
            pictureKey: 'other',
          }))
        : []),
    ]?.filter(el => el);

    /**
     * 组合作品上传所需要的数据
     */
    let option = {
      firstDraftWorkId: ids == 'undefined' ? '' : ids,

      worksInfo: {
        ...worksData,
        ...values,
        ...setAddressValue(values?.code1 ?? []),
        creationTime: values?.creationTime ? moment(values?.creationTime).format('YYYY-MM-DD') : '',
        id,
      },
      worksPicture,
      worksEnclosures: worksData.worksEnclosures?.map(el => ({
        fileId: el.value,
      })),
    };

    /**
     * 删除无用数据
     */
    delete option?.worksInfo.code1;
    delete option?.worksInfo.imprintingImgs;

    if (isnext) {
      option = {
        ...option,
        authorId: worksData.authorId,
        entryId: worksData.entryId,
        exhibitionId: worksData.exhibitionId,
      };
      console.log(option);

      generationUploadWorksInfo(option).then(res => {
        if (res?.responseCode == 200) {
          message.success('作品保存成功');
          goBack();
        }
      });
    } else {
      if (id) {
        /**
         * 如果有id则为编辑数据
         */
        updateWorksInfo(option).then(res => {
          if (res?.responseCode == 200) {
            message.success('作品修改成功');
            goBack();
          }
        });
      } else {
        insertWorksInfo(option).then(res => {
          if (res?.responseCode == 200) {
            message.success('作品保存成功');
            goBack();
          }
        });
      }
    }

    dispatch({
      type: 'addworks/fetch',
    });
  };

  /**
   * 成功之后跳转的页面
   */
  const goBack = () => {
    history.go(isnext ? -1 : -2);
  };

  useEffect(() => {
    /**
     * 编辑的话回显所有数据
     */
    if (id) {
      queryByIdWorksInfo({ id }).then(res => {
        if (res?.responseCode == 200) {
          let data = res?.data;
          let imprintingImgs: any = data?.worksPicture
            ?.filter((el: any) => el.pictureKey == 'other')
            .map((el: any, index: number) => ({
              key: index + 1,
              value: el.pictureId,
            }));

          form.setFieldsValue({
            ...data?.worksInfo,
            creationTime: data?.worksInfo?.creationTime ? moment(data?.worksInfo?.creationTime) : undefined,
            code1: setAddressList(data?.worksInfo),
            imprintingImgs,
          });
        }
      });
    }
  }, []);

  return (
    <div className="works_table">
      <Form labelCol={{ span: 6 }} wrapperCol={{ span: 12 }} layout="horizontal" onFinish={onFinish} form={form}>
        <PageTitle title={'印作品上传'} />
        <TagTitle title={'实物图片'} />
        <div className="export_list">
          <Form.Item label="" name="imprintingImgs">
            <UplodFile
              render={
                <div style={{ color: '#cbcbcb' }}>
                  <PlusOutlined style={{ fontSize: 50 }} />
                </div>
              }
              disabled={disableds}
              limit={100}
            />
          </Form.Item>
        </div>
        <div className="hr"></div>
        <div className="works_form">
          <TagTitle title={'创作信息'} />
          <Form.Item label="创作时间" name="creationTime">
            <DatePicker disabled={disableds} style={{ width: 180 }} placeholder="请选择创作时间" />
          </Form.Item>
          <div className="works_form">
            <Form.Item label="创作地点" name="code1">
              <AddressSelect disabled={disableds} width={100} />
            </Form.Item>
            <Form.Item label=" " colon={false} name="address">
              <Input disabled={disableds} allowClear placeholder="请输入详细地址" />
            </Form.Item>
          </div>
          <Form.Item label="指导老师" name="guidanceTeacher">
            <Input disabled={disableds} style={{ width: 180 }} placeholder="请输入指导老师姓名" allowClear />
          </Form.Item>
          <Form.Item label="老师简介" name="teacherProfile">
            <Input.TextArea autoSize={{ minRows: 5, maxRows: 6 }} placeholder="请输入老师简介。。。" allowClear disabled={disableds} />
          </Form.Item>
          {area.map(el => (
            <Form.Item className="printing" key={el.value + '1231321_123123'} label={el.name} name={el.value}>
              <Input allowClear disabled={disableds} placeholder={'请输入' + el.name} />
            </Form.Item>
          ))}
        </div>
        <div className="hr"></div>
        <div className="add">
          <Button
            className="btn_cold"
            onClick={() => {
              history.go(-1);
            }}>
            上一步
          </Button>
          {disableds ? (
            <Button
              className="btn_cold"
              onClick={() => {
                history.go(-2);
              }}>
              取消
            </Button>
          ) : (
            <Button className="btn_red" htmlType="submit">
              提交
            </Button>
          )}
        </div>
      </Form>
    </div>
  );
};

interface connectState {
  addworks: any;
}
export default connect(({ addworks }: connectState) => ({ worksData: addworks.worksData }))(AddWorksTwo);
